﻿
@inject IHttpService _httpService

@inject ILocalStorageService _localStorage


@inject NavigationManager NavigationManager
@inject IPopupService PopupService


<CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="创建抽奖"/>

<AutoSaveTip TItem="EditLotteryModel" Item="Model" DataLoaded="DataLoaded" @ref="autoSave" />
<div>
    @if (isReady == false)
    {
        <CnGalWebSite.Components.Progressings.ProgressingCard Page Fill />
    }
    else
    {

        <CnGalWebSite.Components.Containers.MasaTitleContainer Title="创建抽奖" Icon="@IconType.Lottery.ToIconString()" Outline>

            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Lotteries.MainCard Model="Model" EntryGameItems="EntryGameItems" Class="mb-4" />
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Lotteries.MainPageCard Model="Model" Class="mb-4" />
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Lotteries.AwardsCard Model="Model" Class="mb-4" />
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Buttons.SubmitButton OnSubmit="OnSubmit" Model="Model" />
        </CnGalWebSite.Components.Containers.MasaTitleContainer>
    }
</div>
@code {
    private EditLotteryModel Model { get; set; } = new EditLotteryModel
        {
            BeginTime = DateTime.Now.ToCstTime(),
            EndTime = DateTime.Now.ToCstTime(),
            LotteryTime = DateTime.Now.ToCstTime(),
        };

    private bool isReady = false;
    private List<string> EntryGameItems { get; set; }


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    AutoSaveTip<EditLotteryModel> autoSave { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                EntryGameItems = await _httpService.GetAsync<List<string>>("api/entries/GetAllEntries/0");

                isReady = true;
                StateHasChanged();
            }
            catch (Exception ex)
            {
                await ErrorHandler.ProcessError(ex, "获取所有词条名称列表失败");
            }
        }
    }
    private async Task OnSubmit()
    {
        try
        {
            var obj = await _httpService.PostAsync<EditLotteryModel, Result>("api/lotteries/CreateLottery", Model);
            //判断结果
            if (obj.Successful == false)
            {

                await PopupService.ToastErrorAsync("创建抽奖失败", obj.Error);
            }
            else
            {
                await PopupService.ToastSuccessAsync("创建抽奖成功", "创建抽奖成功");
                NavigationManager.NavigateTo( "/lotteries/index/" + obj.Error);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "创建抽奖失败");
        }
    }

    private void DataLoaded(EditLotteryModel model)
    {
        isReady = false;
        StateHasChanged();
        Model = model;
        isReady = true;
        StateHasChanged();

    }

}
